﻿using UnityEngine;
using System.Collections;


public class Unit : MonoBehaviour {
	public GameObject obj;
	public GameObject selectorGUI;
	public GameObject turret;
	public GameObject deathFX;
	private Vector3 dmgLoc;
	private Quaternion defaultTurretPos;
	public Vector3 turretUp;
	public NavMeshAgent myAgent;
	public Player owner;
	private Renderer selectionFX;
	private Vector3 screenCoords;
	public UnitType type= UnitType.Unit;
	public float health = 20f;
	public float speed = 10f;
	public int goldValue=5;
	public float maxVelocity=20f; 
	public AudioClip shotClip;
	public AudioClip deathClip;
	public float attackRange = 50f;
	public float attackSpeed = .5f;
	public float attackDamage = 10f;
	public Group myGroup=null;
	private float lastShot = 0f;
	public Unit currentTarget;
	private Vector3 targetPoint= new Vector3(0,0,0);
	public GameObject lasers;
	//private LineRenderer laserShotLine;                 // Reference to the laser shot line renderer.
	//private Light laserShotLight;                       // Reference to the laser shot light.
	//public float flashIntensity = 3f;                   // The intensity of the light when the shot happens.
	//public float fadeSpeed = 10f;                       // How fast the light will fade after the shot.

	/*void Awake()
	{
		if(GetComponent<LineRenderer>() != null)
		{
			laserShotLine = GetComponent<LineRenderer>();
			laserShotLight = laserShotLine.gameObject.light;
			// The line renderer and light are off to start.
			laserShotLine.enabled = false;
			laserShotLight.intensity = 0f;
		}
	}*/

	public void target(Vector3 targ){
		if(myAgent!=null){
			myAgent.SetDestination(targ);
			myAgent.updateRotation=false;
		}
		//targetPoint=targ; 
	}
	
	void Start(){
		selectionFX = (Renderer)selectorGUI.renderer;
		if(turret!=null)
			defaultTurretPos=turret.transform.localRotation;
		Transform o =obj.transform.FindChild("Damage");
		if(o!=null){
			dmgLoc=o.transform.localPosition;
		}
	}
	public bool isSelected(){
		return selectionFX.enabled;	
	}
	public bool isDead(){
		return health<=0f;	
	}
	public Vector3 getScreenCoords(){
		return Camera.main.WorldToScreenPoint(obj.transform.position);	
	}
	public void displaySelection(bool on){
		if(selectionFX)
			selectionFX.enabled=on;
	}
	
	public void takeDamage(float damage)
	{
		health = health - damage;
		if (lastShot > attackSpeed)
						lastShot = 0;
		if(health <= 0f)
		{
			Transform o =obj.transform.FindChild("Damage");
			if(o!=null){
				o.gameObject.GetComponent<ParticleSystem>().Clear(false);
			}
			owner.getUnits ().Remove (this);
			owner.getSelectedUnits().Remove (this);
			myGroup=null;
			if(this.type == UnitType.Building)
			{	
				if(deathFX!=null){
					GameObject tst =(GameObject)Instantiate(deathFX,obj.transform.position,obj.transform.rotation);
					tst.renderer.material.color=owner.myColor;
				}
				GameObject resultText = GameObject.Find ("ResultText");
				if(this.owner.ToString().Equals ("Player"))
				{
					resultText.guiText.text = "YOU LOSE";
				}
				else
				{
					resultText.guiText.text = "VICTORY!";
				}
				resultText.GetComponent<EndGame>().gameOver = true;
			}
			else if(deathFX!=null)
				Instantiate(deathFX,obj.transform.position,obj.transform.rotation);
			if(deathClip!=null)
				AudioSource.PlayClipAtPoint (deathClip, obj.transform.position);
			Destroy(transform.root.gameObject);
		}else{
			Transform o =obj.transform.FindChild("Damage");
			if(o!=null){
				o.transform.localPosition=dmgLoc+Random.insideUnitSphere*.5f;
				o.gameObject.GetComponent<ParticleSystem>().Play(false);
			}
		}
	}
	public void relax(){
		targetPoint= obj.transform.position;
	}
	public void awake(){
		if (lastShot > attackSpeed)
						lastShot = 0;
	}
	void updateAttack(){
		if(lastShot <= 0 )
		{
			Attack(currentTarget);
		}
		else lastShot = lastShot - Time.deltaTime;
		Vector3 tst = currentTarget.obj.transform.position-obj.transform.position; 
		tst.y=0;
		if(tst.magnitude>.01f && type!=UnitType.Building){
			if(turret==null){
				
				Quaternion q = obj.transform.rotation;
				q.SetLookRotation(tst,Vector3.up);
				obj.transform.rotation=Quaternion.Lerp(obj.transform.rotation,q,15*Time.deltaTime); 
			}else{
				tst = currentTarget.obj.transform.position-turret.transform.position; 
				tst.y=0;
				Quaternion q = turret.transform.rotation;
				q.SetLookRotation(tst,turretUp);
				turret.transform.rotation=Quaternion.Lerp(turret.transform.rotation,q,15*Time.deltaTime); 
			}
		}
	}
	void findTarget(){
		currentTarget=null;
		Collider[] data = Physics.OverlapSphere(obj.transform.position,attackRange,1<<LayerMask.NameToLayer("Units"));
		foreach(Collider c in data){
			if(c.transform.parent!=null){
				Component comp=c.transform.parent.GetComponent("Unit");
				if(comp!=null){
					Unit u =(Unit)comp;
					if(u.owner!=owner){
						currentTarget=u;
						break;
					}
				}
			}
		}
	}
	void FixedUpdate(){
		if(obj.rigidbody!=null){
			obj.rigidbody.velocity*=.4f;
		}

		if(currentTarget!=null && !currentTarget.isDead() && (currentTarget.obj.transform.position-obj.transform.position).magnitude<attackRange){
			updateAttack();
		}
		else{
			if(myAgent!=null){
				Quaternion q = obj.transform.rotation;
				Vector3 tst = myAgent.steeringTarget-obj.transform.position; 
				tst.y=0;
				if(tst.magnitude>1f){
					q.SetLookRotation(tst,Vector3.up);
					obj.transform.rotation=Quaternion.Slerp(obj.transform.rotation,q,5*Time.deltaTime);
				}
				//else
					//myAgent.Stop();
			}
			if(turret!=null && type!=UnitType.Building){
				turret.transform.localRotation=Quaternion.Lerp(turret.transform.localRotation,defaultTurretPos,2*Time.deltaTime); 
			}
			Vector3 d=(targetPoint-obj.transform.position);
			if(myAgent==null &&  d.magnitude>.1f && targetPoint.magnitude>.1f){
				float dist=d.magnitude;
				d.Normalize();
				if(obj.rigidbody!=null){
					if(speed*.05f>dist){
						obj.rigidbody.velocity+=d/Time.deltaTime*.05f;
					}else
						obj.rigidbody.velocity+=d*speed/Time.deltaTime*.05f;

				}
			}
			if(lastShot<=0){
				findTarget();
				if(currentTarget==null)
					lastShot+=2;
			}
			else lastShot = lastShot - Time.deltaTime;
		}
	}
	void Attack(Unit obj)
	{
		lastShot = attackSpeed;
		obj.takeDamage (attackDamage);
		ShotEffects(obj);
		if(obj.isDead()){
			owner.gold+=obj.goldValue;
		}
	}
	
	void ShotEffects(Unit obj)
	{
		/*// Set the initial position of the line renderer to the position of the muzzle.
		laserShotLine.SetPosition(0, laserShotLine.transform.position);
		
		// Set the end position of the player's centre of mass.
		laserShotLine.SetPosition(1, obj.transform.position + Vector3.up * 1.5f);
		
		// Turn on the line renderer.
		laserShotLine.enabled = true;
		
		// Make the light flash.
		laserShotLight.intensity = flashIntensity;*/
			Vector3 pos = obj.obj.transform.position;
		if(obj.obj.transform.Find("Damage")!=null)
			pos=obj.obj.transform.Find ("Damage").position;
		if(lasers!=null){
			foreach(LineRenderer laserShot in lasers.GetComponentsInChildren<LineRenderer>()){
				laserShot.SetPosition(0,laserShot.transform.position);
				laserShot.SetPosition(1,pos);
				laserShot.enabled=true;
			}
		}
		AudioSource.PlayClipAtPoint (shotClip, obj.obj.transform.position);
	}
}
